<?php

namespace backend\models;

use Yii;
use yii\web\UploadedFile;

/**
 * This is the model class for table "common_image".
 *
 * @property int $id
 * @property string|null $filename
 */
class CommonImage extends \yii\db\ActiveRecord
{
    public $imageFile;

    const BUCKET_NAME = 'ogikm-img';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'common_image';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['filename', 'size_px'], 'string', 'max' => 255],
            [['comment'], 'string', 'max' => 512],
            [['size_b'], 'integer'],
            [['imageFile'], 'file', 'extensions' => 'jpg, png'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'filename' => 'Имя файла',
            'imageFile' => 'Изображение',
            'size_px' => 'Ширина и высота (px)',
            'size_b' => 'Размер',
            'comment' => 'Комментарий',
        ];
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        $this->deleteImageFile($this->filename);
        
        return true;
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        if($insert)
        {
            if($this->imageFile)
            {
                $this->processCoverImage();   
            }
        }
        else
        {
            if($this->imageFile)
            {
                $this->deleteImageFile($this->filename);
                $this->processCoverImage();
            }
        }
        
        return true;
    }

    public function processCoverImage()
    {
        $imageData = getimagesize($this->imageFile->tempName);

        if(!$this->filename)
        {
            $generatedName = $this->generateFileName($this->imageFile);
            $this->filename = $generatedName;
        }           

        $this->size_px = $imageData[0] . ' x ' .  $imageData[1];
        $this->size_b = $this->imageFile->size;

        $this->uploadImage($this->imageFile, $this->filename);
    }

    private function deleteImageFile($fileName)
    {
        if($fileName)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($fileName)->inBucket(self::BUCKET_NAME)->execute();
        }
    }

    private function uploadImage($file, $fileName)
    {
        if($file)
        {
            $s3 = Yii::$app->get('s3');
            $result = $s3->commands()->upload($fileName, $file->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
        }
    }

    private function generateFileName($file)
    {
        return uniqid() . '.' . $file->extension;
    }
}
